package com.test21_常用类;

import java.lang.ref.Cleaner;

/**
 * Cleaner，回收处理类
 */
public class Demo05_Cleaner {

    public static void main(String[] args) {
//        test1();
        test2();
    }

    /**
     * JDK9之前，通过finialize()方法进行回收处理
     */
    public static void test1() {
        Book book = new Book();
        book.read();
        book = null;
        System.gc();
    }

    /**
     * JDK9之后，不建议使用finialize()方法，通过Cleaner来实现
     */
    public static void test2() {
        Book2 book = new Book2();
        try (ThreadCleaner bc = new ThreadCleaner(book)) {
            book.read();
        } catch (Exception e) {
        }
    }
}

class Book {
    public Book() {
        System.out.println("【构造】用心编写了一本优秀的原创科技图书。");
    }

    public void read() {
        System.out.println("【读书】认真学习李兴华老师的编程技术课程。");
    }

    @Override
    protected void finalize() throws Throwable {
        System.out.println("【析构】认真学习完毕，需要努力消化技术概念。");
    }
}

class Book2 implements Runnable {
    public Book2() {
        System.out.println("【构造】用心编写了一本优秀的原创科技图书。");
    }

    public void read() {
        System.out.println("【读书】认真学习李兴华老师的编程技术课程。");
    }

    @Override
    public void run() {
        System.out.println("【析构】认真学习完毕，需要努力消化技术概念。");
    }
}

class ThreadCleaner implements AutoCloseable {
    private static final Cleaner cleaner = Cleaner.create();    // 回收对象
    private Cleaner.Cleanable cleanable;    // 回收对象管理

    public ThreadCleaner(Book2 book) {
        this.cleanable = cleaner.register(this, book);  // 注册一个回收线程
    }

    @Override
    public void close() throws Exception {
        this.cleanable.clean();  // 释放时进行垃圾的清除
    }
}
